package com.heima.wemedia.gateway.filter;


import com.heima.wemedia.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class WmUserFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        RequestPath path = exchange.getRequest().getPath();///wemedia/api/v1/channel/list
        String url = path.pathWithinApplication().toString();
//        String url = path.toString();
        ServerHttpResponse response = exchange.getResponse();
        if (url.contains("login/in")){
            //放行登录请求
            return chain.filter(exchange);
        }
        //判断token
        String token = exchange.getRequest().mutate().build().getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            //令牌为空
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            // 检测令牌状态
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i==0||i==-1){
                //令牌有效
                Integer userId = (Integer) claimsBody.get("id");
                log.info("find wmUserid:{} form url:{}",userId,url);
                // 增强请求头
                ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", userId+"");
                }).build();
                //放入请求头
                exchange.mutate().request(request).build();
                //放行
                return chain.filter(exchange);
            }else {
                //请登录
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        String s = exchange.getRequest().getURI().toString();//http://localhost:6001/admin/api/v1/channel/list
    }

    /**
     * 设置过滤器的排序规则
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
